<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Django开发知识点 | Depicter</title><meta name="author" content="fanhao"><meta name="copyright" content="fanhao"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="Django开发知识点基础篇1. 什么是Django?它的主要特点是什么?​	Django是Python的一个Web框架，用于快速开发Web应用程序，主要特点包括：  完全基于MVC模式，易于维护和拓展； 自带ORM（对象关系映射）库，简化了数据库操作； 具有良好的安全性和可拓展性，支持多种身份验证和授权方式； 具有丰富的第三方插件和应用生态系统  2. Django的模型(Model)是什么?如">
<meta property="og:type" content="article">
<meta property="og:title" content="Django开发知识点">
<meta property="og:url" content="https://crappier.github.io/2023/05/20/Django%E5%BC%80%E5%8F%91%E7%9F%A5%E8%AF%86%E7%82%B9/index.html">
<meta property="og:site_name" content="Depicter">
<meta property="og:description" content="Django开发知识点基础篇1. 什么是Django?它的主要特点是什么?​	Django是Python的一个Web框架，用于快速开发Web应用程序，主要特点包括：  完全基于MVC模式，易于维护和拓展； 自带ORM（对象关系映射）库，简化了数据库操作； 具有良好的安全性和可拓展性，支持多种身份验证和授权方式； 具有丰富的第三方插件和应用生态系统  2. Django的模型(Model)是什么?如">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://crappier.github.io/img/cover/cover_6.jpg">
<meta property="article:published_time" content="2023-05-20T06:49:35.000Z">
<meta property="article:modified_time" content="2023-05-20T08:00:41.280Z">
<meta property="article:author" content="fanhao">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://crappier.github.io/img/cover/cover_6.jpg"><link rel="shortcut icon" href="/img/dinosaur.png"><link rel="canonical" href="https://crappier.github.io/2023/05/20/Django%E5%BC%80%E5%8F%91%E7%9F%A5%E8%AF%86%E7%82%B9/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Django开发知识点',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-05-20 16:00:41'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">5</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('/img/cover/cover_6.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Depicter"><span class="site-name">Depicter</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Django开发知识点</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-20T06:49:35.000Z" title="发表于 2023-05-20 14:49:35">2023-05-20</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-05-20T08:00:41.280Z" title="更新于 2023-05-20 16:00:41">2023-05-20</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Django开发知识点"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Django开发知识点"><a href="#Django开发知识点" class="headerlink" title="Django开发知识点"></a>Django开发知识点</h1><h2 id="基础篇"><a href="#基础篇" class="headerlink" title="基础篇"></a>基础篇</h2><h3 id="1-什么是Django-它的主要特点是什么"><a href="#1-什么是Django-它的主要特点是什么" class="headerlink" title="1. 什么是Django?它的主要特点是什么?"></a>1. 什么是Django?它的主要特点是什么?</h3><p>​	Django是Python的一个Web框架，用于快速开发Web应用程序，主要特点包括：</p>
<ul>
<li>完全基于<code>MVC</code>模式，易于维护和拓展；</li>
<li>自带<code>ORM</code>（对象关系映射）库，简化了数据库操作；</li>
<li>具有良好的安全性和可拓展性，支持多种身份验证和授权方式；</li>
<li>具有丰富的第三方插件和应用生态系统</li>
</ul>
<h3 id="2-Django的模型-Model-是什么-如何定义一个Django模型"><a href="#2-Django的模型-Model-是什么-如何定义一个Django模型" class="headerlink" title="2. Django的模型(Model)是什么?如何定义一个Django模型?"></a>2. Django的模型(Model)是什么?如何定义一个Django模型?</h3><p>​	Django的模型（Model）是用于表示数据库中的表的类，每个Django模型都有唯一的标识符（一般是自增的整数id），以及一组字段，这些字段定义了表中的数据。</p>
<p>​	定义一个Django模型需要遵循以下步骤：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 1. 导入必备模块</span></span><br><span class="line"><span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line"></span><br><span class="line"><span class="comment"># 2. 创建类，继承自models.Model</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyModel</span>(models.Model):</span><br><span class="line">    <span class="comment"># 自定义字段</span></span><br><span class="line">    f1 = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment"># 重写get_id方法，得到唯一标识</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_id</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> self.pk</span><br><span class="line">    <span class="comment"># 定义表名</span></span><br><span class="line">    <span class="keyword">class</span> <span class="title class_">Meta</span>:</span><br><span class="line">        db_table = <span class="string">&#x27;mymodel&#x27;</span></span><br><span class="line">        <span class="comment"># 添加其他字段等信息，如：</span></span><br><span class="line">        fields = <span class="string">&#x27;__all__&#x27;</span></span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line"><span class="comment"># 3. 在settings.py中配置数据库链接与其他设置</span></span><br><span class="line">DATABASES = &#123;</span><br><span class="line">    <span class="string">&#x27;default&#x27;</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;ENGINE&#x27;</span>: <span class="string">&#x27;django.db.backends.mysql&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;NAME&#x27;</span>: <span class="string">&#x27;mydatabase&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;USER&#x27;</span>: <span class="string">&#x27;mydatabaseuser&#x27;</span>, // 如果使用MySQL数据库，需要指定用户名</span><br><span class="line">        <span class="string">&#x27;PASSWORD&#x27;</span>: <span class="string">&#x27;mypassword&#x27;</span>, // 如果使用MySQL数据库，需要指定密码</span><br><span class="line">        <span class="string">&#x27;HOST&#x27;</span>: <span class="string">&#x27;localhost&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;PORT&#x27;</span>: <span class="string">&#x27;&#x27;</span>, // 如果使用本地开发服务器，可以省略端口号，默认为<span class="number">3306</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<h3 id="3-什么是Django的URL路由-URL-Routing-如何定义URL路由"><a href="#3-什么是Django的URL路由-URL-Routing-如何定义URL路由" class="headerlink" title="3. 什么是Django的URL路由(URL Routing)?如何定义URL路由?"></a>3. 什么是Django的URL路由(URL Routing)?如何定义URL路由?</h3><p>​	Django中的URL路由定义了如何将HTTP请求映射到相应的视图函数（view）</p>
<p>​	定义URL路由需要遵循以下步骤：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 导入必备模块</span></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path</span><br><span class="line"><span class="keyword">from</span> . <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line"><span class="comment"># eg: 1</span></span><br><span class="line">url = [</span><br><span class="line">    path(<span class="string">&#x27;/index/&#x27;</span>,views.index),</span><br><span class="line">]</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">在eg: 1中，path()函数的第一个参数是URL路径/index/,第二个参数是视图函数views.index。这意味着当用户访问/index/时，Django会自动调用views.index函数并传递URL路径作为参数。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># eg: 2</span></span><br><span class="line">url = [</span><br><span class="line">    path(<span class="string">&#x27;&#x27;</span>, views.index, name=<span class="string">&#x27;index&#x27;</span>),</span><br><span class="line">    path(<span class="string">&#x27;new_page/&#x27;</span>, views.new_page, name=<span class="string">&#x27;new_page&#x27;</span>),</span><br><span class="line">]</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">在eg: 2中，第一个URL路由将所有URL请求映射到视图函数views.index,第二个URL路由将所有URL请求映射到视图函数views.new_page,并且它们的名称分别为index和new_page。这样可以更方便地在URLconfs中引用这些路由。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h3 id="4-如何在Django中定义视图-View"><a href="#4-如何在Django中定义视图-View" class="headerlink" title="4. 如何在Django中定义视图(View)?"></a>4. 如何在Django中定义视图(View)?</h3><p>​	Django中的视图（view）用于处理HTTP请求并生成响应函数</p>
<p>​	定义视图需要遵循以下步骤：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 导入必备模块</span></span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="comment"># 1. 创建视图函数</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">index</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">return</span> HttpResponse(<span class="string">&quot;Hello Django!&quot;</span>)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">index()函数接受一个名为request的参数，该参数代表HTTP请求对象。函数返回一个HTTP响应对象，其中包含字符串&quot;Hello Django!&quot;。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 2. 在URLconfs中将视图函数映射到URL路径中</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path</span><br><span class="line"><span class="keyword">from</span> . <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">&#x27;&#x27;</span>, views.index, name=<span class="string">&#x27;index&#x27;</span>),</span><br><span class="line">]</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">path()函数的第一个参数是URL路径/,第二个参数是视图函数views.index,并且它们的名称相同。这意味着当用户访问/时，Django会自动调用views.index()函数并传递URL路径作为参数。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h3 id="5-如何在Django中定义模板-Template"><a href="#5-如何在Django中定义模板-Template" class="headerlink" title="5. 如何在Django中定义模板(Template)?"></a>5. 如何在Django中定义模板(Template)?</h3><p>​	在Django中，模板（Template）是用于呈现HTML代码的文件</p>
<p>​	定义模板需要遵循以下步骤：</p>
<p>​	1. 在Django项目的templates目录下创建一个新的模板文件，如: my_template.html。在模板文件中编写HTML代码，可以使用Django提供的模板标签和过滤器来添加动态内容和样式</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;% extends &#x27;base.html&#x27; %&#125;</span><br><span class="line"></span><br><span class="line">&#123;% block content %&#125;</span><br><span class="line">  <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Welcome to my website!<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; message &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">&#123;% endblock %&#125;</span><br></pre></td></tr></table></figure>

<p>​	在这个例子中，<code>&#123;% extends 'base.html' %&#125;</code>语句指定了基础模板，该模板将用于扩展当前模板。<code>&#123;% block content %&#125;</code>语句定义了一个名为<code>content</code>的块，该块将在模板中呈现为HTML代码。在这个例子中，我们使用<code>&#123;&#123; message &#125;&#125;</code>变量来显示一个来自视图函数的动态消息。</p>
<pre><code>2. 在Django项目的`urls.py`文件中将模板文件与URL路径相关联。
</code></pre>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path</span><br><span class="line"><span class="keyword">from</span> . <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">&#x27;mypage/&#x27;</span>, views.index, name=<span class="string">&#x27;index&#x27;</span>),</span><br><span class="line">    path(<span class="string">&#x27;&#x27;</span>, include(<span class="string">&#x27;myapp.urls&#x27;</span>)),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>​	在这个例子中，<code>path()</code>函数的第一个参数是URL路径<code>/mypage/</code>,第二个参数是视图函数<code>views.index</code>,并且它们的名称相同。这意味着当用户访问<code>/mypage/</code>时，Django会自动调用<code>views.index()</code>函数并传递URL路径作为参数。同时，我们使用<code>include()</code>函数将包含其他URLconfs的模块导入到当前模块中。</p>
<h3 id="6-如何在Django中进行表单处理-Form-Processing"><a href="#6-如何在Django中进行表单处理-Form-Processing" class="headerlink" title="6. 如何在Django中进行表单处理(Form Processing)?"></a>6. 如何在Django中进行表单处理(Form Processing)?</h3><p>​	Django中，表单处理（Form Processing）是用于处理用户提交的表单数据的过程</p>
<p>​	进行表单处理需要遵循以下步骤：</p>
<p>​	1. 在Django项目的<code>forms.py</code>文件中定义一个表单类。表单类是用于表示一个表单的数据模型，它包含了表单字段和其他必要的元数据。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django <span class="keyword">import</span> forms</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ContactForm</span>(forms.Form):</span><br><span class="line">    name = forms.CharField(max_length=<span class="number">100</span>)</span><br><span class="line">    email = forms.EmailField()</span><br><span class="line">    message = forms.CharField(widget=forms.Textarea)</span><br></pre></td></tr></table></figure>

<p>​	在这个例子中，<code>ContactForm</code>类继承自<code>forms.Form</code>,并且定义了三个表单字段：<code>name</code>、<code>email</code>和<code>message</code>。每个表单字段都有一个相应的类型和属性，例如<code>CharField</code>表示文本字段，<code>EmailField</code>表示电子邮件字段，<code>Textarea</code>表示多行文本区域。</p>
<pre><code> 2. 在Django项目的视图函数中处理表单数据，视图函数是用于处理HTTP请求并生成响应的函数。在处理表单数据时，需要从请求对象中获取表单数据，并对其进行验证和处理。
</code></pre>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"><span class="keyword">from</span> .forms <span class="keyword">import</span> ContactForm</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">contact</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">&#x27;POST&#x27;</span>:</span><br><span class="line">        form = ContactForm(request.POST)</span><br><span class="line">        <span class="keyword">if</span> form.is_valid():</span><br><span class="line">            <span class="comment"># 处理表单数据</span></span><br><span class="line">            name = form.cleaned_data[<span class="string">&#x27;name&#x27;</span>]</span><br><span class="line">            email = form.cleaned_data[<span class="string">&#x27;email&#x27;</span>]</span><br><span class="line">            message = form.cleaned_data[<span class="string">&#x27;message&#x27;</span>]</span><br><span class="line">            <span class="comment"># 发送邮件或其他操作</span></span><br><span class="line">            <span class="keyword">return</span> HttpResponse(<span class="string">&#x27;Thank you for contacting us!&#x27;</span>)</span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">&#x27;Failed to contact, please try again!&#x27;</span>)</span><br><span class="line">    form = ContactForm()</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&#x27;contact.html&#x27;</span>, &#123;<span class="string">&#x27;form&#x27;</span>: form&#125;)</span><br></pre></td></tr></table></figure>

<p>​	在这个例子中，<code>contact()</code>函数首先检查HTTP请求的方法是否为POST。如果是POST请求，则创建一个<code>ContactForm</code>对象并使用<code>cleaned_data()</code>方法从请求中获取表单数据。如果表单数据验证通过，则可以对其进行进一步的处理，例如将数据保存到数据库或发送电子邮件，最后返回一个HTTP响应。如果是GET请求，则返回一个<code>contact.html</code>页面，并携带<code>form</code>以渲染表单页面。</p>
<h3 id="7-如何在Django中进行用户认证-User-Authentication"><a href="#7-如何在Django中进行用户认证-User-Authentication" class="headerlink" title="7. 如何在Django中进行用户认证(User Authentication)?"></a>7. 如何在Django中进行用户认证(User Authentication)?</h3><p>​	Django中的用户认证是用于检验用户身份的过程</p>
<p>​	实现用户认证需要遵循以下步骤：</p>
<p>​	1. 在Django项目的<code>settings.py</code>文件中配置用户认证系统。Django提供了多种用户认证方式，例如基于Cookie的认证、基于HTTP基本认证的认证、LDAP认证等，在<code>settings.py</code>文件中配置相关的设置。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># settings.py</span></span><br><span class="line">SESSION_COOKIE_SECURE = <span class="literal">True</span></span><br><span class="line">SESSION_COOKIE_AGE = <span class="number">60</span> * <span class="number">24</span> * <span class="number">7</span> <span class="comment"># one week</span></span><br><span class="line">AUTHENTICATION_BACKENDS = (</span><br><span class="line">    <span class="string">&#x27;django.contrib.auth.backends.ModelBackend&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;myapp.backends.CustomBackend&#x27;</span>,</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment"># myapp/backends.py</span></span><br><span class="line"><span class="keyword">from</span> django.contrib.auth <span class="keyword">import</span> get_user_model</span><br><span class="line"><span class="keyword">from</span> django.contrib.auth.backends <span class="keyword">import</span> ModelBackend</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">CustomBackend</span>:</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">authenticate</span>(<span class="params">self, request</span>):</span><br><span class="line">        username = request.POST[<span class="string">&#x27;username&#x27;</span>]</span><br><span class="line">        password = request.POST[<span class="string">&#x27;password&#x27;</span>]</span><br><span class="line">        user = get_user_model().objects.get(username=username)</span><br><span class="line">        <span class="keyword">if</span> user <span class="keyword">and</span> user.check_password(password):</span><br><span class="line">            <span class="keyword">return</span> user</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">authenticate_header</span>(<span class="params">self, request</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;Username&#x27;</span></span><br></pre></td></tr></table></figure>

<p>​	在这个例子中，<code>settings.py</code>文件定义了一个使用<code>SessionCookie</code>和<code>CustomBackend</code>的用户认证系统。<code>AUTHENTICATION_BACKENDS</code>设置指定了Django将使用哪些认证后端来验证用户身份。<code>CustomBackend</code>是一个自定义的认证后端类，它实现了<code>authenticate()</code>和<code>authenticate_header()</code>方法，用于验证用户身份和生成认证头。在<code>authenticate()</code>方法中，我们从请求中获取用户名和密码，并使用<code>get_user_model()</code>函数获取当前使用的User模型类。然后，我们使用该模型类的<code>objects.get()</code>方法查找具有指定用户名的用户对象。如果找到了匹配的用户对象并且密码正确，则返回该用户对象；否则返回<code>None</code>。在<code>authenticate_header()</code>方法中，我们返回一个字符串，表示Django将使用该字符串作为认证头发送给客户端。通常情况下，这个字符串应该是一个简单的字符串，例如“Username”。</p>
<p>​	2. 在视图函数中处理用户认证，视图函数是用于处理HTTP请求并生成响应的函数。在处理用户认证时，需要从请求中获取用户名和密码，并将其传递给自定义的认证后端进行验证。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render, redirect</span><br><span class="line"><span class="keyword">from</span> django.contrib.auth <span class="keyword">import</span> authenticate, login</span><br><span class="line"><span class="keyword">from</span> myapp.forms <span class="keyword">import</span> LoginForm</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">login</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">&#x27;POST&#x27;</span>:</span><br><span class="line">        form = LoginForm(request.POST)</span><br><span class="line">        <span class="keyword">if</span> form.is_valid():</span><br><span class="line">            username = form.cleaned_data[<span class="string">&#x27;username&#x27;</span>]</span><br><span class="line">            password = form.cleaned_data[<span class="string">&#x27;password&#x27;</span>]</span><br><span class="line">            user = authenticate(request, username=username, password=password)</span><br><span class="line">            <span class="keyword">if</span> user <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">                login(request, user) <span class="comment"># log the user in automatically</span></span><br><span class="line">                <span class="keyword">return</span> redirect(<span class="string">&#x27;home&#x27;</span>) <span class="comment"># redirect to the home page after login</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                form.add_error(<span class="string">&quot;username&quot;</span>, <span class="string">&quot;Invalid username or password&quot;</span>)</span><br><span class="line">                <span class="keyword">return</span> render(request, <span class="string">&#x27;login.html&#x27;</span>, &#123;<span class="string">&#x27;form&#x27;</span>: form&#125;)</span><br><span class="line">    form = LoginForm()</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&#x27;login.html&#x27;</span>, &#123;<span class="string">&#x27;form&#x27;</span>: form&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="8-如何在Django中进行文件上传-File-Uploading"><a href="#8-如何在Django中进行文件上传-File-Uploading" class="headerlink" title="8. 如何在Django中进行文件上传(File Uploading)?"></a>8. 如何在Django中进行文件上传(File Uploading)?</h3><p>​	1. 在Django的<code>settings.py</code>文件中配置文件上传路径和最大文件大小。例如，以下是一个使用<code>MEDIA_ROOT</code>和<code>MEDIA_URL</code>变量来配置文件上传路径的示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># settings.py</span></span><br><span class="line">MEDIA_ROOT = <span class="string">&#x27;/path/to/media/root/&#x27;</span></span><br><span class="line">MEDIA_URL = <span class="string">&#x27;/media/&#x27;</span></span><br></pre></td></tr></table></figure>

<p>​	2. 创建一个Django视图函数来处理文件上传请求。该视图函数应该接受一个名为<code>request</code>的请求对象作为参数，并返回一个HTTP响应。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render, redirect</span><br><span class="line"><span class="keyword">from</span> django.conf <span class="keyword">import</span> settings</span><br><span class="line"><span class="keyword">from</span> django.core.files.storage <span class="keyword">import</span> FileSystemStorage</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">upload</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">&#x27;POST&#x27;</span> <span class="keyword">and</span> request.FILES[<span class="string">&#x27;file&#x27;</span>]:</span><br><span class="line">        file = request.FILES[<span class="string">&#x27;file&#x27;</span>]</span><br><span class="line">        filepath = <span class="string">&#x27;/path/to/upload/directory/&#x27;</span> + file.name</span><br><span class="line">        <span class="keyword">with</span> <span class="built_in">open</span>(filepath, <span class="string">&#x27;wb+&#x27;</span>) <span class="keyword">as</span> destination:</span><br><span class="line">            <span class="keyword">for</span> chunk <span class="keyword">in</span> file.chunks():</span><br><span class="line">                destination.write(chunk)</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">&#x27;/success/&#x27;</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">&#x27;upload.html&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">success</span>(<span class="params">request</span>):</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">&#x27;success.html&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>​	在这个例子中，<code>upload()</code>视图函数首先检查请求是否包含名为<code>file</code>的文件。如果请求包含文件并且文件有效，则将文件保存到指定的目录中。最后，该视图函数重定向到一个成功页面。<code>success()</code>视图函数用于显示成功消息。</p>
<pre><code>3. 在HTML模板文件中添加表单元素以允许用户上传文件。
</code></pre>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span> <span class="attr">action</span>=<span class="string">&quot;&#123;% url &#x27;upload&#x27; %&#125;&quot;</span> <span class="attr">enctype</span>=<span class="string">&quot;multipart/form-data&quot;</span>&gt;</span></span><br><span class="line">    &#123;% csrf_token %&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;file&quot;</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span>&gt;</span>Upload<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>​	在这个例子中，<code>&#123;% csrf_token %&#125;</code>标签用于添加CSRF令牌以保护表单免受跨站点请求伪造攻击。<code>enctype=&quot;multipart/form-data&quot;</code>属性用于指定表单数据是二进制数据而不是文本数据。</p>
<h3 id="9-如何在Django中进行数据迁移-Data-Migration"><a href="#9-如何在Django中进行数据迁移-Data-Migration" class="headerlink" title="9. 如何在Django中进行数据迁移(Data Migration)?"></a>9. 如何在Django中进行数据迁移(Data Migration)?</h3><p>[pycharm操作]</p>
<ul>
<li><p>在Pycharm终端输入指令：</p>
<ul>
<li><pre><code class="shell">python manage.py makemigrations
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">-   ```shell</span><br><span class="line">    python manage.py migrate</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://crappier.github.io">fanhao</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://crappier.github.io/2023/05/20/Django%E5%BC%80%E5%8F%91%E7%9F%A5%E8%AF%86%E7%82%B9/">https://crappier.github.io/2023/05/20/Django%E5%BC%80%E5%8F%91%E7%9F%A5%E8%AF%86%E7%82%B9/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://crappier.github.io" target="_blank">Depicter</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Python/">Python</a></div><div class="post_share"><div class="social-share" data-image="/img/cover/cover_6.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2024/03/06/OWASP-TOP-10/" title="OWASP-TOP-10"><img class="cover" src="/img/cover/cover_2.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">OWASP-TOP-10</div></div></a></div><div class="next-post pull-right"><a href="/2023/05/16/Go%E8%AF%AD%E8%A8%80%E5%AD%A6%E4%B9%A0/" title="Go语言学习"><img class="cover" src="/img/cover/cover_4.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Go语言学习</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/04/10/Python%E7%9A%84%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6/" title="Python的垃圾回收机制"><img class="cover" src="/img/cover/cover_1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-10</div><div class="title">Python的垃圾回收机制</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">fanhao</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">5</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/fanhao0416"><i class="fab fa-gitee"></i><span>联系我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/fanhao0416" target="_blank" title="Gitee"><i class="fab fa-git" style="color: #DC143C;"></i></a><a class="social-icon" href="mailto:2039216364@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2039216364&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">沧海易幻莫同，世人皆平庸</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Django%E5%BC%80%E5%8F%91%E7%9F%A5%E8%AF%86%E7%82%B9"><span class="toc-number">1.</span> <span class="toc-text">Django开发知识点</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E7%A1%80%E7%AF%87"><span class="toc-number">1.1.</span> <span class="toc-text">基础篇</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AFDjango-%E5%AE%83%E7%9A%84%E4%B8%BB%E8%A6%81%E7%89%B9%E7%82%B9%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">1.1.1.</span> <span class="toc-text">1. 什么是Django?它的主要特点是什么?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-Django%E7%9A%84%E6%A8%A1%E5%9E%8B-Model-%E6%98%AF%E4%BB%80%E4%B9%88-%E5%A6%82%E4%BD%95%E5%AE%9A%E4%B9%89%E4%B8%80%E4%B8%AADjango%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.1.2.</span> <span class="toc-text">2. Django的模型(Model)是什么?如何定义一个Django模型?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E4%BB%80%E4%B9%88%E6%98%AFDjango%E7%9A%84URL%E8%B7%AF%E7%94%B1-URL-Routing-%E5%A6%82%E4%BD%95%E5%AE%9A%E4%B9%89URL%E8%B7%AF%E7%94%B1"><span class="toc-number">1.1.3.</span> <span class="toc-text">3. 什么是Django的URL路由(URL Routing)?如何定义URL路由?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%A6%82%E4%BD%95%E5%9C%A8Django%E4%B8%AD%E5%AE%9A%E4%B9%89%E8%A7%86%E5%9B%BE-View"><span class="toc-number">1.1.4.</span> <span class="toc-text">4. 如何在Django中定义视图(View)?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%A6%82%E4%BD%95%E5%9C%A8Django%E4%B8%AD%E5%AE%9A%E4%B9%89%E6%A8%A1%E6%9D%BF-Template"><span class="toc-number">1.1.5.</span> <span class="toc-text">5. 如何在Django中定义模板(Template)?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%A6%82%E4%BD%95%E5%9C%A8Django%E4%B8%AD%E8%BF%9B%E8%A1%8C%E8%A1%A8%E5%8D%95%E5%A4%84%E7%90%86-Form-Processing"><span class="toc-number">1.1.6.</span> <span class="toc-text">6. 如何在Django中进行表单处理(Form Processing)?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E5%A6%82%E4%BD%95%E5%9C%A8Django%E4%B8%AD%E8%BF%9B%E8%A1%8C%E7%94%A8%E6%88%B7%E8%AE%A4%E8%AF%81-User-Authentication"><span class="toc-number">1.1.7.</span> <span class="toc-text">7. 如何在Django中进行用户认证(User Authentication)?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E5%A6%82%E4%BD%95%E5%9C%A8Django%E4%B8%AD%E8%BF%9B%E8%A1%8C%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0-File-Uploading"><span class="toc-number">1.1.8.</span> <span class="toc-text">8. 如何在Django中进行文件上传(File Uploading)?</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-%E5%A6%82%E4%BD%95%E5%9C%A8Django%E4%B8%AD%E8%BF%9B%E8%A1%8C%E6%95%B0%E6%8D%AE%E8%BF%81%E7%A7%BB-Data-Migration"><span class="toc-number">1.1.9.</span> <span class="toc-text">9. 如何在Django中进行数据迁移(Data Migration)?</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2024/03/12/Nmap%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97/" title="Nmap使用指南"><img src="/img/cover/cover_2.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nmap使用指南"/></a><div class="content"><a class="title" href="/2024/03/12/Nmap%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97/" title="Nmap使用指南">Nmap使用指南</a><time datetime="2024-03-12T02:38:29.000Z" title="发表于 2024-03-12 10:38:29">2024-03-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2024/03/10/TCP%E5%8D%8F%E8%AE%AE/" title="TCP协议"><img src="/img/cover/cover_9.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="TCP协议"/></a><div class="content"><a class="title" href="/2024/03/10/TCP%E5%8D%8F%E8%AE%AE/" title="TCP协议">TCP协议</a><time datetime="2024-03-10T08:15:52.000Z" title="发表于 2024-03-10 16:15:52">2024-03-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2024/03/06/%E5%B8%B8%E7%94%A8%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8%E8%AE%BE%E5%A4%87/" title="常用网络安全设备"><img src="/img/cover/cover_6.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="常用网络安全设备"/></a><div class="content"><a class="title" href="/2024/03/06/%E5%B8%B8%E7%94%A8%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8%E8%AE%BE%E5%A4%87/" title="常用网络安全设备">常用网络安全设备</a><time datetime="2024-03-06T00:58:05.000Z" title="发表于 2024-03-06 08:58:05">2024-03-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2024/03/06/%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95/" title="渗透测试"><img src="/img/cover/cover_9.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="渗透测试"/></a><div class="content"><a class="title" href="/2024/03/06/%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95/" title="渗透测试">渗透测试</a><time datetime="2024-03-06T00:57:01.000Z" title="发表于 2024-03-06 08:57:01">2024-03-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2024/03/06/OWASP-TOP-10/" title="OWASP-TOP-10"><img src="/img/cover/cover_2.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="OWASP-TOP-10"/></a><div class="content"><a class="title" href="/2024/03/06/OWASP-TOP-10/" title="OWASP-TOP-10">OWASP-TOP-10</a><time datetime="2024-03-06T00:55:41.000Z" title="发表于 2024-03-06 08:55:41">2024-03-06</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2025 By fanhao</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="true" data-click="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>